﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Odbc;
using System.Data;
using WLMCoreLibrary;
using System.Web;
using System.Configuration;
using System.IO;
using System.Web.SessionState;
using MiWebSite_Core;

namespace MWS_AddDirectory
{
    public class DeDominio : BaseClass
    {
        #region private fields
        protected String _dominio;
        protected String _logotipo;
        protected String _slogan;
        protected String _estadisticas;
        protected String _keywords;
        protected String _description;
        protected String _mapPoint;
        protected String _mapsApiKey;
        protected String _twitterAccount;
        protected String _twitterPassword;
        protected int _idDomain;
        protected int _idParentDomain;
        protected int _idGrandParentDomain;
        protected String _bitlyApiKey;
        protected String _longName;
        private bool _activo;
        private String _oauth_token;
        private String _oauth_token_secret;
        private int _idTwitterApplication;
        private string _facebook;
        #endregion

        #region public properties
        public String dominio {get;set; }
        public String logotipo {get;set; }
        public String slogan {get;set; }
        public String estadisticas {get;set; }
        public String keywords {get;set; }
        public String description {get;set; }
        public String mapPoint {get;set; }
        public String mapsApiKey {get;set; }
        public String twitterAccount {get;set; }
        public String twitterPassword {get;set; }
        public int idDomain {get;set; }
        public int idParentDomain {get;set; }
        public int idGrandParentDomain {get;set; }
        public String bitlyApiKey {get;set; }
        public String longName {get;set; }
        public bool activo {get;set; }
        public String oauth_token {get;set; }
        public String oauth_token_secret {get;set; }
        public int idTwitterApplication {get;set; }
        public string facebook {get;set; }
        #endregion

        #region constructors
        public DeDominio(ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            id = classBinder.NewRecord("DOMINIOS");
            string queryString = "";
            queryString = "SELECT * FROM DOMINIOS WHERE id='" + id + "'";
            GetRecord(queryString);
        }

        public DeDominio(string dom, ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
            queryString = "SELECT * FROM DOMINIOS WHERE dominio='" + dom + "' order by id ASC";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            this.GetRecord(queryString);
        }

        public DeDominio(int registryId, ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
            queryString = "SELECT * FROM DOMINIOS WHERE id='" + registryId + "'";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            this.GetRecord(queryString);
        }
        #endregion

        #region public methods

        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM DOMINIOS WHERE id='" + id + "'";
            ConexionDBInterna.ExecuteCommand(queryString);

        }
        #endregion


        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]);  if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];
                
                    
                if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
                    idUsuario = (System.Int32)reader["idUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("dominio")))
                    dominio = (System.String)reader["dominio"];
                if (!reader.IsDBNull(reader.GetOrdinal("logotipo")))
                    logotipo = (System.String)reader["logotipo"];
                if (!reader.IsDBNull(reader.GetOrdinal("slogan")))
                    slogan = (System.String)reader["slogan"];
                if (!reader.IsDBNull(reader.GetOrdinal("estadisticas")))
                    estadisticas = (System.String)reader["estadisticas"];
                if (!reader.IsDBNull(reader.GetOrdinal("keywords")))
                    keywords = (System.String)reader["keywords"];
                if (!reader.IsDBNull(reader.GetOrdinal("description")))
                    description = (System.String)reader["description"];
                if (!reader.IsDBNull(reader.GetOrdinal("mapPoint")))
                    mapPoint = (System.String)reader["mapPoint"];
                if (!reader.IsDBNull(reader.GetOrdinal("mapsApiKey")))
                    mapsApiKey = (System.String)reader["mapsApiKey"];
                if (!reader.IsDBNull(reader.GetOrdinal("twitterAccount")))
                    twitterAccount = (System.String)reader["twitterAccount"];
                if (!reader.IsDBNull(reader.GetOrdinal("twitterPassword")))
                    twitterPassword = (System.String)reader["twitterPassword"];
                if (!reader.IsDBNull(reader.GetOrdinal("idDomain")))
                    idDomain = (System.Int32)reader["idDomain"];
                if (!reader.IsDBNull(reader.GetOrdinal("idParentDomain")))
                    idParentDomain = (System.Int32)reader["idParentDomain"];
                if (!reader.IsDBNull(reader.GetOrdinal("idGrandParentDomain")))
                    idGrandParentDomain = (System.Int32)reader["idGrandParentDomain"];
                if (!reader.IsDBNull(reader.GetOrdinal("bitlyApiKey")))
                    bitlyApiKey = (System.String)reader["bitlyApiKey"];
                if (!reader.IsDBNull(reader.GetOrdinal("longName")))
                    longName = (System.String)reader["longName"];
                if (!reader.IsDBNull(reader.GetOrdinal("activo")))
                    activo = Convert.ToBoolean(reader["activo"]);
                if (!reader.IsDBNull(reader.GetOrdinal("oauth_token")))
                    oauth_token = (System.String)reader["oauth_token"];
                if (!reader.IsDBNull(reader.GetOrdinal("oauth_token_secret")))
                    oauth_token_secret = (System.String)reader["oauth_token_secret"];
                if (!reader.IsDBNull(reader.GetOrdinal("idTwitterApplication")))
                    idTwitterApplication = (System.Int32)reader["idTwitterApplication"];
                if (!reader.IsDBNull(reader.GetOrdinal("facebook")))
                    facebook = (System.String)reader["facebook"];
            }
        }


        protected override void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE DOMINIOS set "); strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); strCommand.Append(",idUsuarioModificacion=\"" + idUsuarioModificacion.ToString() + "\"");
            
            strCommand.Append(",dominio=\"" + WLMFunctions.comillas(dominio) + "\"");
            strCommand.Append(",logotipo=\"" + WLMFunctions.comillas(logotipo) + "\"");
            strCommand.Append(",slogan=\"" + WLMFunctions.comillas(slogan) + "\"");
            strCommand.Append(",estadisticas=\"" + WLMFunctions.comillas(estadisticas) + "\"");
            strCommand.Append(",keywords=\"" + WLMFunctions.comillas(keywords) + "\"");
            strCommand.Append(",description=\"" + WLMFunctions.comillas(description) + "\"");
            strCommand.Append(",mapPoint=\"" + WLMFunctions.comillas(mapPoint) + "\"");
            strCommand.Append(",mapsApiKey=\"" + WLMFunctions.comillas(mapsApiKey) + "\"");
            strCommand.Append(",twitterAccount=\"" + WLMFunctions.comillas(twitterAccount) + "\"");
            strCommand.Append(",twitterPassword=\"" + WLMFunctions.comillas(twitterPassword) + "\"");
            strCommand.Append(",idDomain='" + idDomain.ToString() + "'");
            strCommand.Append(",idParentDomain='" + idParentDomain.ToString() + "'");
            strCommand.Append(",idGrandParentDomain='" + idGrandParentDomain.ToString() + "'");
            strCommand.Append(",bitlyApiKey=\"" + WLMFunctions.comillas(bitlyApiKey) + "\"");
            strCommand.Append(",longName=\"" + WLMFunctions.comillas(longName) + "\"");
            strCommand.Append(",activo='" + Convert.ToInt16(activo) + "'");
            strCommand.Append(",oauth_token=\"" + WLMFunctions.comillas(oauth_token) + "\"");
            strCommand.Append(",oauth_token_secret=\"" + WLMFunctions.comillas(oauth_token_secret) + "\"");
            strCommand.Append(",idTwitterApplication='" + idTwitterApplication.ToString() + "'");
            strCommand.Append(",facebook=\"" + WLMFunctions.comillas(facebook) + "\"");
            strCommand.Append(" WHERE id='" + id + "'");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion
    }

    /// <summary>
    /// Dominio Actual de el Directorio DE
    /// </summary>
    public class DeCurrentDomain
    {
        public static string DomainName
        {
            get
            {
                if (HttpContext.Current.Application["dominio" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["dominio" + CurrentDomainName].ToString();

            }
        }

        public static string Ciudad
        {
            get
            {
                if (HttpContext.Current.Application["ciudad" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["ciudad" + CurrentDomainName].ToString();

            }
        }


        public static string SubDomain
        {
            get
            {

                if (HttpContext.Current.Application["dominio" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                string _subdomain;
                string[] subDomSeparator = { HttpContext.Current.Application["dominio" + CurrentDomainName].ToString() };
                string _host = HttpContext.Current.Request.Url.Host;
               _subdomain = _host.Split(subDomSeparator, StringSplitOptions.None)[0].Replace(".", "");
                if (_subdomain == "")
                   _subdomain = "www";
                return _subdomain;

            }
        }

        public static string CurrentDomainName
        {
            get
            {
                //if (HttpContext.Current.Session["actualDomainName"] == null)
                //{
                //    char[] separador=new char[] {'.'};  
                //    string _host = HttpContext.Current.Request.Url.Host;
                //    string[] cadena= _host.Split(separador,2);
                //    HttpContext.Current.Session["actualDomainName"] = _host;
                //    if(cadena.Length>1)
                //        HttpContext.Current.Session["actualDomainName"] = cadena[1];
                //    if (HttpContext.Current.Session["actualDomainName"].ToString().Length>3)
                //        if (HttpContext.Current.Session["actualDomainName"].ToString().Substring(1, 3) == "com")
                //            HttpContext.Current.Session["actualDomainName"] = _host;
                //}
                //return HttpContext.Current.Session["actualDomainName"].ToString();
                string acualDomainName = "";
                    char[] separador = new char[] { '.' };
                    string _host = HttpContext.Current.Request.Url.Host;
                    string[] cadena = _host.Split(separador, 2);
                    acualDomainName = _host;
                    if (cadena.Length > 1)
                        acualDomainName = cadena[1];
                    if (acualDomainName.Length > 3)
                    {
                        if (acualDomainName.Substring(1, 3) == "com")
                            acualDomainName = _host;
                    }
                    else
                    { acualDomainName = _host; }
                    return acualDomainName;
            }
        }

        public static int IdentificadorDominio
        {
            get
            {
                if (HttpContext.Current.Application["idDomain" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return Convert.ToInt32(HttpContext.Current.Application["idDomain" + CurrentDomainName]);
            }
        }

        private static void GetDeCurrentDomainInfo()
        {
            dbConnector conn = new dbConnector();
            string host;
            host = HttpContext.Current.Request.Url.Host;
            char[] subDomSeparator = { '.' };
            string _sub = host.Split(subDomSeparator, 2)[1];
            
            DeDominio dominioActual = new DeDominio(_sub,ref conn);
            
            //HttpContext.Current.Response.Write(dominioActual.id);
            //HttpContext.Current.Response.End();
            if (dominioActual.id != 0)
            {
                GetData(dominioActual);

            }
            else
            {
                dominioActual = new DeDominio(host,ref conn);
                if (dominioActual.id != 0)
                    GetData(dominioActual);
            }
conn.CloseConnection();
            ////HttpContext.Current.Response.Write("Datos de Dominio Cargados");
        }

        private static void GetData(DeDominio dominioActual)
        {

            HttpContext.Current.Application["dominio" + CurrentDomainName] = dominioActual.dominio;
            HttpContext.Current.Application["LogotipoDominio" + CurrentDomainName] = dominioActual.logotipo;
            HttpContext.Current.Application["SloganDominio" + CurrentDomainName] = dominioActual.slogan;
            HttpContext.Current.Application["EstadisticasDominio" + CurrentDomainName] = dominioActual.estadisticas;
            HttpContext.Current.Application["KeywordsDominio" + CurrentDomainName] = dominioActual.keywords;
            HttpContext.Current.Application["DescripcionDominio" + CurrentDomainName] = dominioActual.description;
            HttpContext.Current.Application["idDominio" + CurrentDomainName] = dominioActual.id;
            HttpContext.Current.Application["MapsApiKey" + CurrentDomainName] = dominioActual.mapsApiKey;
            HttpContext.Current.Application["MapPoint" + CurrentDomainName] = dominioActual.mapPoint;
            HttpContext.Current.Application["twitterAccount" + CurrentDomainName] = dominioActual.twitterAccount;
            HttpContext.Current.Application["twitterPassword" + CurrentDomainName] = dominioActual.twitterPassword;
            HttpContext.Current.Application["bitlyApiKey" + CurrentDomainName] = dominioActual.bitlyApiKey;
            HttpContext.Current.Application["idDomain" + CurrentDomainName] = dominioActual.idDomain;
            HttpContext.Current.Application["idParentDomain" + CurrentDomainName] = dominioActual.idParentDomain;
            HttpContext.Current.Application["estadisticas" + CurrentDomainName] = dominioActual.estadisticas;
            HttpContext.Current.Application["idGrandParentDomain" + CurrentDomainName] = dominioActual.idGrandParentDomain;
            HttpContext.Current.Application["ciudad" + CurrentDomainName] = dominioActual.longName;
            HttpContext.Current.Application["TwitterAppId" + CurrentDomainName] = dominioActual.idTwitterApplication;
            HttpContext.Current.Application["oauth_token" + CurrentDomainName] = dominioActual.oauth_token;
            HttpContext.Current.Application["oauth_token_secret" + CurrentDomainName] = dominioActual.oauth_token_secret;
            HttpContext.Current.Application["facebook" + CurrentDomainName] = dominioActual.facebook;
        }


        public static string estadisticas
        {
            get
            {
                if (HttpContext.Current.Application["estadisticas" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["estadisticas" + CurrentDomainName].ToString();
                //return "";

            }
        }

        public static string MapsApiKey
        {
            get
            {
                if (HttpContext.Current.Application["MapsApiKey" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["MapsApiKey" + CurrentDomainName].ToString();
                //return "";

            }
        }

        public static string MapPoint
        {
            get
            {
                if (HttpContext.Current.Application["MapPoint" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["MapPoint" + CurrentDomainName].ToString();

            }
        }

        public static string twitterAccount
        {
            get
            {
                if (HttpContext.Current.Application["twitterAccount" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["twitterAccount" + CurrentDomainName].ToString();

            }
        }

        public static string twitterPassword
        {
            get
            {
                if (HttpContext.Current.Application["twitterPassword" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["twitterPassword" + CurrentDomainName].ToString();

            }
        }

        public static string bitlyApiKey
        {
            get
            {
                if (HttpContext.Current.Application["bitlyApiKey" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["bitlyApiKey" + CurrentDomainName].ToString();

            }
        }

        public static int idParentDomain
        {
            get
            {
                if (HttpContext.Current.Application["idParentDomain" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return Convert.ToInt32(HttpContext.Current.Application["idParentDomain" + CurrentDomainName]);

            }
        }

        public static int TwitterAppId
        {
            get
            {
                if (HttpContext.Current.Application["TwitterAppId" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return Convert.ToInt32(HttpContext.Current.Application["TwitterAppId" + CurrentDomainName]);

            }
        }

        public static string oauth_token
        {
            get
            {
                if (HttpContext.Current.Application["oauth_token" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["oauth_token" + CurrentDomainName].ToString();

            }
        }

        public static string oauth_token_secret
        {
            get
            {
                if (HttpContext.Current.Application["oauth_token_secret" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["oauth_token_secret" + CurrentDomainName].ToString();

            }
        }
        
        public static string facebook
        {
            get
            {
                if (HttpContext.Current.Application["facebook" + CurrentDomainName] == null)
                    GetDeCurrentDomainInfo();
                return HttpContext.Current.Application["facebook" + CurrentDomainName].ToString();

            }
        }






    }

    public static class DeFunctions
    {
        public static string LoadTemplate(string fileName, string TituloAdicional, string AditionalKeywords,ref dbConnector MiWebSiteConnection)
        {
            string skinPath =  ConfigurationManager.AppSettings["skinPath"];
            string siteURL = ConfigurationManager.AppSettings["MainSiteURL"];
            string sitePath = ConfigurationManager.AppSettings["SitePath"];

            string siteDomain = DeCurrentDomain.DomainName;
            string siteDomain2 = siteDomain.Substring(2);
            //string DomainDescription = "";
            string skinSource = "";




            #region session cookie

            //if (HttpContext.Current.Handler is IRequiresSessionState || HttpContext.Current.Handler is IReadOnlySessionState)
            //{

            //    /// Ensure ASP.NET Session Cookies are accessible throughout the subdomains.



            //    if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null && HttpContext.Current.Session != null && HttpContext.Current.Session.SessionID != null)
            //    {
            //        HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value = HttpContext.Current.Session.SessionID;

            //        HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Domain = "." + DeCurrentDomain.DomainName; // the full stop prefix denotes all sub domains

            //        HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Path = "/"; //default session cookie path root       
            //    }
            //}
#endregion







            if (HttpContext.Current.Request.Cookies["recordarme"] != null && CurrentClient.Id==0)
            {
                MiWebSiteUser cliente = new MiWebSiteUser(HttpContext.Current.Request.Cookies["usuario"].Value,ref  MiWebSiteConnection);
                if (cliente.password == HttpContext.Current.Request.Cookies["password"].Value)
                {
                    CurrentUser.LogOnUser(cliente,true);
                }
            }

            //if (HttpContext.Current.Request.Browser.ScreenPixelsWidth<=640)
            if (HttpContext.Current.Request.Browser.IsMobileDevice)
                fileName = fileName.Split('.')[0] + "Movil." + fileName.Split('.')[1];
            else if (DeCurrentDomain.SubDomain=="m")
                fileName = fileName.Split('.')[0] + "Movil." + fileName.Split('.')[1];

            if (HttpContext.Current.Application[fileName] == null || HttpContext.Current.IsDebuggingEnabled)
            {
                try
                {
                    TextReader fileReader = new StreamReader(sitePath + "/" + skinPath + fileName);
                    skinSource = fileReader.ReadToEnd();
                    fileReader.Close();
                    HttpContext.Current.Application.Add(fileName, skinSource);
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("Plantilla " + fileName + " no encontrada, intente mas tarde <br>" + ex.Message);
                }
            }
            else
                skinSource = HttpContext.Current.Application[fileName].ToString();

            string includesHead = "<link rel='stylesheet' href='/includes/css/calendar-system.css' />\n<script language=\"javascript\" src=\"/includes/js/jquery.js\"> </script> \n<script language='javascript' src='/includes/js/jquery.droppy.js'></script>\n<script language='javascript' src='/includes/js/jquery.pngFix.js'></script>\n<script language='javascript' src='/includes/js/js.js'></script>\n<script type='text/javascript'>\n$(function() {\n    $('#MainMenu').droppy();\n	$(document).pngFix(); \n  });\n</script> ";
            string includesBody = "";
            string menuPrincipal = "";// CrearMenuSuperior(BuscarRegistro("categorias","nombre","mapa del sitio",MiWebSiteConnection),0,"MainMenu","",MiWebSiteConnection);
            string menuInferior = "";// CrearMenuInferior(BuscarRegistro("categorias", "nombre", "mapa del sitio", MiWebSiteConnection), 0, "MenuBottom", "", MiWebSiteConnection); ;
            string subMenus = Convert.ToString(HttpContext.Current.Application["subMenus"]);


            if (CurrentUser.UserName != "")
                skinSource = skinSource.Replace("PANELUSUARIO", "Bienvenido " + CurrentUser.UserName + " <a href='/panel/'>ir al panel de control</a>");
            else
                skinSource = skinSource.Replace("PANELUSUARIO", "");



            // includesHead = includesHead + "<script type='text/javascript' src='/includes/js/prototype.js'></script><script type='text/javascript' src='/includes/js/effects.js'></script><script type='text/javascript' src='/includes/js/scriptaculous.js'></script><script type='text/javascript' src='/includes/js/js.js'></script><link rel='stylesheet' href='/includes/css/cropper.css' /><link rel='stylesheet' href='/includes/css/calendar-system.css' /><script type='text/javascript' src='/includes/js/cropper.js'></script>";

            skinSource = skinSource.Replace("[INCLUDESHEAD]", includesHead);
            skinSource = skinSource.Replace("[INCLUDESBODY]", includesBody);
            skinSource = skinSource.Replace("[TITULOWEBSITE]", TituloAdicional + " ");
            skinSource = skinSource.Replace("[MENUPRINCIPAL]", menuPrincipal);
            skinSource = skinSource.Replace("[SUBMENUS]", "");
            skinSource = skinSource.Replace("[MENUINFERIOR]", menuInferior);
            skinSource = skinSource.Replace("[NOMBREDOMINIO]", siteDomain);
            //skinSource = skinSource.Replace("[DESCRIPCION]", DomainDescription);
            skinSource = skinSource.Replace("[NOMBREDOMINIO2]", siteDomain2);
            skinSource = skinSource.Replace("[SUBDOMINIO]", DeCurrentDomain.SubDomain);
            skinSource = skinSource.Replace("[CIUDAD]", DeCurrentDomain.Ciudad);
            Categoria categoria = new Categoria(DeCurrentDomain.SubDomain, true,ref MiWebSiteConnection);
            if (categoria.id != 0)
                skinSource = skinSource.Replace("[CATEGORIA]", categoria.nombreCategoria);
            else
                skinSource = skinSource.Replace("[CATEGORIA]", DeCurrentDomain.SubDomain);
            skinSource = skinSource.Replace("[SLOGAN]", "");
            skinSource = skinSource.Replace("{LISTADO}", ListadoCategoriasDirectorio(MiWebSiteConnection));
            skinSource = skinSource.Replace("[ESTADISTICAS]", DeCurrentDomain.estadisticas);
            skinSource = skinSource.Replace("[GoogleMapsApiKey]", DeCurrentDomain.MapsApiKey);
            if (skinSource.Contains("{URL}"))
                skinSource = skinSource.Replace("{URL}", siteURL);
            if (skinSource.Contains("{RUTA}"))
                skinSource = skinSource.Replace("{RUTA}", siteURL + skinPath);
            //if(HttpContext.Current.Application["keywords"]==null)
            //    new MiWebSiteKeyWordCollection(MiWebSiteConnection).GenerarKeywordsApplication();
            //skinSource = skinSource.Replace("[KEYWORDS]", "");
            skinSource = skinSource.Replace("[GENERATOR]", DeCurrentDomain.DomainName);
            if (CurrentUser.Email != null)
                skinSource = skinSource.Replace("[USUARIOACTUAL]", CurrentUser.UserName + " - <a href='/login.aspx?logout=1'>Cerrar Sesion</a>");
            else
                skinSource = skinSource.Replace("[USUARIOACTUAL]", "Invitado");


            return skinSource;
        }

        public static string ListadoCategoriasDirectorio(dbConnector ConexionDB)
        {
            StringBuilder listaCategorias = new StringBuilder();
            CategoriaCollection categoriasDirectorio = new CategoriaCollection(new Random(),ref ConexionDB);
            listaCategorias.Append("<ul id='CatList'>");

            foreach (Categoria dirCat in categoriasDirectorio.Elementos)
            {
                listaCategorias.Append("<li><a href='http://" + dirCat.SystemName + "." + DeCurrentDomain.DomainName + "'>" + dirCat.nombreCategoria + "</a></li>");
            }
            listaCategorias.Append("</ul>");
            return listaCategorias.ToString();
        }

        //public static bool Twitear(string Mensaje,dbConnector conexion)
        //{
        //    try
        //    {
        //        TwitterAPI tw = new TwitterAPI();
        //        Twitterapplication twiapp = new Twitterapplication(DeCurrentDomain.TwitterAppId,ref conexion);
        //        tw.AuthenticateWith(twiapp.ConsumerKey, twiapp.ConsumerSecret, DeCurrentDomain.oauth_token, DeCurrentDomain.oauth_token_secret);
        //        string statusUpdate = Mensaje;
        //        TwitterStatus status = tw.Update(statusUpdate);
        //        return true;
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}
    }


    public class Twitterapplication : BaseClass
    {
        #region private fields
        private String _Nombre;
        private String _ConsumerKey;
        private String _ConsumerSecret;
        #endregion

        #region public properties
        public String Nombre {get;set; }
        public String ConsumerKey {get;set; }
        public String ConsumerSecret {get;set; }
        #endregion

        #region constructors
        public Twitterapplication(ref dbConnector ConexionDB)
        {
            
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            id = classBinder.NewRecord("TWITTERAPPLICATION");
            string queryString = "";
            queryString = "SELECT * FROM TWITTERAPPLICATION WHERE id='" + id + "'";
            GetRecord(queryString);
        }

        public Twitterapplication(int registryId, ref dbConnector ConexionDB)
        {
            
            string queryString = "";
            queryString = "SELECT * FROM TWITTERAPPLICATION WHERE id='" + registryId + "'";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            this.GetRecord(queryString);
        }
        public Twitterapplication(DataRow dataRow, ref dbConnector ConexionDB)
        {
            
            this.GetRecord(dataRow);
        }
        #endregion

        #region public methods


        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM TWITTERAPPLICATION WHERE id='" + id + "'";
            ConexionDBInterna.ExecuteCommand(queryString);

        }
        #endregion


        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]);
                if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion")))
                    fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]);
                if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
                    idUsuario = (System.Int32)reader["idUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion")))
                    idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];
                if (!reader.IsDBNull(reader.GetOrdinal("Nombre")))
                    Nombre = (System.String)reader["Nombre"];
                if (!reader.IsDBNull(reader.GetOrdinal("ConsumerKey")))
                    ConsumerKey = (System.String)reader["ConsumerKey"];
                if (!reader.IsDBNull(reader.GetOrdinal("ConsumerSecret")))
                    ConsumerSecret = (System.String)reader["ConsumerSecret"];
            }
        }


        private void GetRecord(DataRow dataRow)
        {
            if (dataRow != null)
            {
                if (dataRow["id"] != null)
                    id = (System.Int32)dataRow["id"];
                if (dataRow["fechaCreacion"] != null)
                    fechaCreacion = (System.DateTime)dataRow["fechaCreacion"];
                if (dataRow["fechaModificacion"] != null)
                    fechaModificacion = (System.DateTime)dataRow["fechaModificacion"];
                if (dataRow["idUsuario"] != null)
                    idUsuario = (System.Int32)dataRow["idUsuario"];
                if (dataRow["idUsuarioModificacion"] != null)
                    idUsuarioModificacion = (System.Int32)dataRow["idUsuarioModificacion"];
                if (dataRow["Nombre"] != null)
                    Nombre = (System.String)dataRow["Nombre"];
                if (dataRow["ConsumerKey"] != null)
                    ConsumerKey = (System.String)dataRow["ConsumerKey"];
                if (dataRow["ConsumerSecret"] != null)
                    ConsumerSecret = (System.String)dataRow["ConsumerSecret"];
            }
        }


        protected override void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE TWITTERAPPLICATION set ");
            strCommand.Append("fechaModificacion='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'");
            strCommand.Append(",idUsuarioModificacion='" + idUsuarioModificacion.ToString() + "'");
            strCommand.Append(",Nombre=\"" + WLMFunctions.comillas(Nombre) + "\"");
            strCommand.Append(",ConsumerKey=\"" + WLMFunctions.comillas(ConsumerKey) + "\"");
            strCommand.Append(",ConsumerSecret=\"" + WLMFunctions.comillas(ConsumerSecret) + "\"");
            strCommand.Append(" WHERE id='" + id + "'");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion
    }




    public class TwitterapplicationCollection
    {
        private List<Twitterapplication> _items;
        public List<Twitterapplication> Elementos {get;set; }
        public TwitterapplicationCollection()
        {
        }
        public TwitterapplicationCollection(ref dbConnector ConexionDB)
        {
            
            string strCommand = "SELECT id FROM TWITTERAPPLICATION ";
            OdbcDataReader dataReader = ConexionDB.ExecuteReader(strCommand);
            Elementos = new List<Twitterapplication>();
            while (dataReader.Read())
            {
                Twitterapplication newItem = new Twitterapplication(Convert.ToInt32(dataReader["id"]),ref ConexionDB);
                Elementos.Add(newItem);
            }
            dataReader.Close();
            dataReader.Dispose();
        }
    }
}
